package com.example.mycontacts;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class EditExistingContact extends Activity {

	private Spinner spinner_categories;
	private String userid;
	private String name;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_existing_contact);
		
		populateEditText();

		addItemsOnSpinnerCats2();
		addListenerOnSpinnerItemSelection2();
		
		final Button button_save = (Button) findViewById(R.id.button_save);
        button_save.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
               updateContact();
            }
        });
        
        final Button button_delete = (Button) findViewById(R.id.button_delete);
        button_delete.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                deleteContact(userid, name);
                }
        });
	}

public void addItemsOnSpinnerCats2() {
		
		spinner_categories = (Spinner) findViewById(R.id.category_spinner);
		List<String> list = new ArrayList<String>();
		
		DBAdapter db = new DBAdapter(this);
		db.open();
		
		//populates the spinner from the list acquired from database
		list = db.getCats();

		db.close();
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, list);
			dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinner_categories.setAdapter(dataAdapter);
	}
	
	public void addListenerOnSpinnerItemSelection2() {
		spinner_categories = (Spinner) findViewById(R.id.category_spinner);
		spinner_categories.setOnItemSelectedListener(new CustomOnItemSelectedListener());
	  }

	public void addListenerOnButton() {
		 
		spinner_categories = (Spinner) findViewById(R.id.category_spinner);
	 
	  }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_edit_existing_contact, menu);
		return true;
	}
	
	public void populateEditText()
	{
		String str;
		Intent intent = getIntent();
		
		userid = intent.getStringExtra("userid");
		
		str = intent.getStringExtra("contactName");
		name = str;
		EditText contactName = (EditText) findViewById(R.id.name);
		contactName.setText(str);
		
		str = intent.getStringExtra("cityStateZip");
		String [] strArray = new String[4];
		
		StringTokenizer token = new StringTokenizer(str, "~|~");
		for(int i=0; token.hasMoreElements(); i++)	
		{
			strArray[i] = token.nextToken();
		}
		EditText cityStateZip = (EditText) findViewById(R.id.address);
		
		
		if(strArray[0] != null)	
			cityStateZip.setText(strArray[0]);
		else
			cityStateZip.setText("");
		
		EditText city = (EditText) findViewById(R.id.city);
		if(strArray[1] != null)
			city.setText(strArray[1]);
		else
			city.setText("");
		
		EditText state = (EditText) findViewById(R.id.state);
		if(strArray[2] != null)
			state.setText(strArray[2]);
		else
			state.setText("");
		
		EditText zip = (EditText) findViewById(R.id.zipcode);
		if(strArray[3] != null)
			zip.setText(strArray[3]);	
		else
			zip.setText("");
		
		str = intent.getStringExtra("phoneNumber");
		EditText phone = (EditText) findViewById(R.id.phoneNumber);
		phone.setText(str);
		
		str = intent.getStringExtra("altPhoneNumber");
		EditText altPhone = (EditText) findViewById(R.id.altPhoneNumber);
		altPhone.setText(str);
		
		str = intent.getStringExtra("email");
		EditText email = (EditText) findViewById(R.id.email);
		email.setText(str);
		
		str = intent.getStringExtra("comments");
		EditText comments = (EditText) findViewById(R.id.comments);
		comments.setText(str);
		
		str = intent.getStringExtra("category");
	}
	
	
	
	public void updateContact()
	{
		
		Information info = new Information();
		String condition;
		
		EditText text = (EditText) findViewById(R.id.name);
		condition = (text.getText().toString());
		
		if(condition.matches(""))
		{
			Toast.makeText(this, "name cannont be empty", Toast.LENGTH_SHORT).show();
		}
		else
		{
			info.setName(text.getText().toString());
			text = (EditText) findViewById(R.id.phoneNumber);
			info.setPhoneNumber(text.getText().toString());
			text = (EditText) findViewById(R.id.altPhoneNumber);
			info.setAltPhone(text.getText().toString());
			text = (EditText) findViewById(R.id.email);
			info.setEmailAddress(text.getText().toString());
			text = (EditText) findViewById(R.id.comments);
			info.setComments(text.getText().toString());

			String str = spinner_categories.getItemAtPosition(spinner_categories.getSelectedItemPosition()).toString();
			info.setCategory(str);
			
			Address addr = new Address();
			text = (EditText) findViewById(R.id.address);
			addr.setStreetAddress(text.getText().toString());
			text = (EditText) findViewById(R.id.city);
			addr.setCity(text.getText().toString());
			text = (EditText) findViewById(R.id.state);
			addr.setState(text.getText().toString());
			text = (EditText) findViewById(R.id.zipcode);
			addr.setZipcode(text.getText().toString());
			
			DBAdapter db = new DBAdapter(this);
			db.open();
			long success = db.updateContact(info, addr, userid);
			db.close();
		
			if(success > 0)
			{
				Toast.makeText(this, "Update Successful", Toast.LENGTH_SHORT).show();
				Intent intent = new Intent(EditExistingContact.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);    
                startActivity(intent);
			}
			else
			{
				Toast.makeText(this, "Update Failed", Toast.LENGTH_SHORT).show();
				Intent intent = new Intent(EditExistingContact.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);    
                startActivity(intent);
			}
		}
	}
	
	@SuppressLint("ShowToast")
	public void deleteContact(final String userid, final String name)
	{
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setMessage("Are you sure you want to delete " + name+"?");
			alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
								@SuppressLint("ShowToast")
								public void onClick(DialogInterface dialog, int id){
									DBAdapter db = new DBAdapter(EditExistingContact.this);
									db.open();
									long success = db.deleteInformation(userid);
									db.close();
									
									if(success > 0)
									{
										Toast.makeText(EditExistingContact.this, name + " was deleted", Toast.LENGTH_SHORT).show();
									}
									else
									{
										Toast.makeText(EditExistingContact.this, "Unable to delete" + name, Toast.LENGTH_SHORT).show();
									}
									Intent intent = new Intent(EditExistingContact.this, MainActivity.class);
					                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);    
					                startActivity(intent);
								}
			});
			alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id){
									dialog.cancel();
									Intent intent = new Intent(EditExistingContact.this, MainActivity.class);
					                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);    
					                startActivity(intent);
								}
			});
			AlertDialog alertMess = alert.create();
			alertMess.show();
		
	}
	

}
